﻿using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace CWM.Skinn
{
    public static partial class SkinnContextCommands
    {
        [CtxMenuItem("Transform/Ensure Unique Names",
            "Duplicates in children are named xxx_#",
            ContextRequirements.Children, 0)]
        public static void TransformOrderedNames()
        {
            const string undoLabel = "Ensure Unique Names";
            foreach (var item in SkinnContext.GetContextItems())
            {
                var context = item.GetComponent<Transform>();
                if (SkinnEx.IsNullOrNotInAScene(context)) continue;
                var t = context.transform.GetAllChildren(false).ToArray();

                var names = new List<string>();
                for (int i = 0; i < t.Length; i++)
                {
                    Undo.RecordObject(t[i].gameObject, undoLabel);
                    t[i].gameObject.name = SkinnEx.GetOrderedName(ref names, t[i].gameObject.name);
                }
            }
            SkinnContext.Finished();
        }

        [CtxMenuItem("Transform/Sort Children",
            "Alphanumeric sorting of all children.",
            ContextRequirements.Children, 0)]
        public static void TransformSort()
        {
            const string undoLabel = "Sort by Name";
            foreach (var item in SkinnContext.GetContextItems())
            {
                var context = item.GetComponent<Transform>();
                if (SkinnEx.IsNullOrNotInAScene(context)) continue;

                foreach (var transform in context.GetAllChildren(true))
                {
                    var childern = new List<Transform>(transform.GetDirectChildren());
                    childern.Sort(0, childern.Count, new SortTransforms());

                    for (int i = 0; i < childern.Count; i++)
                    {
                        Undo.RecordObject(childern[i], undoLabel);
                        childern[i].SetSiblingIndex(i);
                    }
                }
            }
            SkinnContext.Finished();
        }

        private static string PadNumbers(string input)
        {
            return Regex.Replace(input, "[0-9]+", match => match.Value.PadLeft(10, '0'));
        }

        private class SortTransforms : IComparer<Transform>
        {
            int IComparer<Transform>.Compare(Transform p1, Transform p2)
            {
                return PadNumbers(p1.name).CompareTo(PadNumbers(p2.name));
            }
        }
    }
}